import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2025-02-27
 * Time: 8:41
 */
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        for (int parent = (usedSize-2)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = 2 * root;

        while (child < usedSize){
            if (elem[child] < elem[child+1]){
                child++;
            }
            //走到这里child下标一定是左右孩子最大值的下标
            if (elem[child] > elem[root]){
                swap(root,child);
                root = child;
                child = 2 * root + 1;
            }else {
                break;
            }
        }
    }

    private void swap(int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while (parent >= 0){
            if (elem[child] > elem[parent]){
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length == usedSize;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public int pollHeap() {
        if (isEmpty()){
            return -1;
        }
        int oldValue = elem[0];
        swap(0,usedSize-1);
        //调整0下标的树
        usedSize--;
        shiftDown(0,usedSize);
        return oldValue;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public void  peekHeap() {
        int end = usedSize - 1;
        while (end > 0){
            swap(0,end);
            shiftDown(0,end);
            end--;
        }
    }
}